<template>
    <div>
        <el-card>
            <el-form :model="state.pageParam.param" ref="queryFormRef" label-width="120" @keyup.enter.native="loadList" >
                <el-row>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" >
                        <el-form-item prop="username" label="用户名">
                            <el-input v-model="state.pageParam.param.username" placeholder="用户名" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
                        <el-form-item prop="staffId" label="员工编号">
                            <el-input v-model="state.pageParam.param.staffId" placeholder="员工编号" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
                        <el-form-item prop="staffName" label="姓名">
                            <el-input v-model="state.pageParam.param.staffName" placeholder="姓名" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
                        <el-form-item prop="orgId" label="组织机构">
                            <el-input v-model="state.pageParam.param.orgName" placeholder="组织机构" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6" v-if="state.istenant && userInfos.tenantId === '1'">
                        <el-form-item prop="tenantId" label="租户">
                            <DicSelect v-model="state.pageParam.param.tenantId" placeholder="请选择租户" isTenantSelect="true" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
                        <el-form-item prop="status" label="用户状态">
                            <DicSelect v-model="state.pageParam.param.status" placeholder="请选择用户状态" dicCode="1002" :excludeIsKey="['100204']" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="btnSearchStyle">
                <el-button type="primary" class="ml7" @click="loadList">
                    <el-icon>
                        <ele-Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
                    <el-icon>
                        <ele-Refresh />
                    </el-icon>
                    重置
                </el-button>
            </div>
        </el-card>
        <el-card>
            <div class="btnStyle">
                <el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
            </div>
            <el-table :data="state.dataList" stripe style="width: 100%" v-loading="state.listLoading">
                <el-table-column prop="username" header-align="center" align="center" label="用户名" />
                <el-table-column prop="staffId" header-align="center" align="center" label="员工编号" />
                <el-table-column prop="staffName" header-align="center" align="center" label="姓名" />
                <el-table-column prop="status" header-align="center" align="center" label="用户状态" column-key="1002" :formatter="formatStatus" />
                <el-table-column prop="orgName" header-align="center" align="center" label="组织机构" />
                <el-table-column prop="tenantName" header-align="center" align="center" label="租户" v-if="state.istenant && userInfos.tenantId === '1'"/>
                <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
                        <el-button type="primary" link @click="resetPasswordHandle(scope.row.id)">重置密码</el-button>
                        <el-button type="primary" link @click="setRoleHandle(scope.row.id)">角色设置</el-button>
                        <el-button type="primary" link @click="setStationHandle(scope.row.id)">岗位设置</el-button>
                        <el-button type="primary" link  @click="setResEditLineHandle(scope.row)"  >设置资源权限</el-button>
                        <el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" :pager-count="5"
                :page-sizes="[10, 50, 200]" v-model:current-page="state.pageParam.page" background
                v-model:page-size="state.pageParam.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="state.total" small>
            </el-pagination>
        </el-card>
        <el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate"
            v-model="state.addOrUpdateVisible">
            <el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef"
                @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
                <el-form-item label="租户" prop="tenantId">
                    <DicSelect v-model="state.submitForm.tenantId" placeholder="请选择租户" isTenantSelect="true" style="width:100%"></DicSelect>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="state.submitForm.username" placeholder="用户名" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="state.submitForm.email" placeholder="邮箱" maxlength="100"></el-input>
                </el-form-item>
                <el-form-item label="用户状态" prop="status">
                    <DicSelect v-model="state.submitForm.status" placeholder="请选择用户状态" dicCode="1002" :excludeIsKey="['100204']" style="width:100%"></DicSelect>
                </el-form-item>
                <el-form-item label="员工编号" prop="staffId">
                    <el-input v-model="state.submitForm.staffId" placeholder="员工编号" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="staffName">
                    <el-input v-model="state.submitForm.staffName" placeholder="姓名" maxlength="50"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="ordernum">
                    <el-input v-model="state.submitForm.ordernum" placeholder="排序" maxlength="67"></el-input>
                </el-form-item>
                <el-form-item label="组织机构" prop="orgId">
                    <OrgSelect v-model="state.submitForm.orgId" placeholder="组织机构" :tenantId="state.submitForm.tenantId"></OrgSelect>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.addOrUpdateVisible = false">取消</el-button>
                    <el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" title="角色设置"
            v-model="state.roleEditVisible">
            <el-transfer v-model="state.userRoleList" :data="state.allRoles" ref="userRoleListRef"/>
            <template #footer>
				<span class="dialog-footer">
					<el-button @click="state.roleEditVisible = false">取消</el-button>
					<el-button type="primary" @click="roleEditSubmit()">确定</el-button>
				</span>
			</template>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" title="岗位设置"
            v-model="state.stationEditVisible">
            <el-tree :data="state.userStationTree" ref="userStationTreeRef" node-key="id" :props="state.userStationTreeProps" 
                show-checkbox  :check-strictly="true"  :highlight-current="true" v-loading="state.userStationTreeLoading" 
                :default-expand-all="true" style="width: 100%;">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.stationEditVisible = false">取消</el-button>
					<el-button type="primary" @click="stationEditSubmit()">确定</el-button>
				</span>
			</template>
        </el-dialog>
        <el-dialog :close-on-click-modal="false" title="设置资源权限" v-model="state.userMenuSetVisible">
			<el-tree :data="state.menuListOnly" ref="treeUserMenuOnlyRef" node-key="id" :props="state.menuListTreeProps"  show-checkbox  
                :check-strictly="false"  :highlight-current="true" v-loading="state.treeLoading" :default-expand-all="true" style="width: 100%;">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.userMenuSetVisible = false">取消</el-button>
					<el-button type="primary" @click="resOnlySubmit()">确定</el-button>
				</span>
			</template>
		</el-dialog>
    </div>
</template>
<script setup lang="ts" name="sysUser">
import { ElMessage, ElTree, ElMessageBox, FormInstance, ElLoading, TransferPropsAlias, ElTransfer } from 'element-plus'
import { ref, reactive, onMounted, defineAsyncComponent } from 'vue'
import { systemApi } from '/@/api/sys/system-api'
import { getDataDictionaryList } from '/@/utils/cacheDic'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia'
//引入组件
const OrgSelect = defineAsyncComponent(() => import('/@/components/orgSelect/index.vue'))
const { userInfos } = storeToRefs(useUserInfo())
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const userStationTreeRef = ref<InstanceType<typeof ElTree>>()
const treeUserMenuOnlyRef = ref<InstanceType<typeof ElTree>>()
const userRoleListRef = ref<InstanceType<typeof ElTransfer>>()
const state = reactive({
    istenant: import.meta.env.VITE_IS_TENANT as Boolean,
    listLoading: false,
    total: 0,
    dataList: [],
    dataListSelections: [],
    dataDictionaryList: {} as any,
    pageParam: {
        page: 1,
        pageSize: 10,
        param: {
            username: '',
            status: '',
            staffId: '',
            staffName: '',
            orgId: '',
            orgName: '',
            tenantId: userInfos.value.tenantId,
        }
    },
    addOrUpdateVisible: false,
    submitForm: {
        id: '',
        username: '',
        password: '',
        salt: '',
        email: '',
        mobile: '',
        status: '',
        createUserId: '',
        createTime: '',
        staffId: '',
        enterpriseId: '',
        enterpriseName: '',
        staffName: '',
        idType: '',
        idNo: '',
        lastChangeder: '',
        lastChangedTime: '',
        lastChangedPwdTime: '',
        errorTime: '',
        loginStatus: '',
        alterTime: '',
        loginTime: '',
        ordernum: '',
        chkStatus: '',
        orgId: '',
        skin: '',
        accountName: '',
        loginTerminal: '',
        tenantId: userInfos.value.tenantId,
    },
    submitFormRule: {
        tenantId: [
            { required: true, message: '请选择租户', trigger: 'blur' }
        ],
        username: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        status: [
            { required: true, message: '请选择用户状态', trigger: 'blur' }
        ],
        staffId: [
            { required: true, message: '员工编号不能为空', trigger: 'blur' }
        ],
        staffName: [
            { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        orgId: [
            { required: true, message: '请选择组织机构', trigger: 'blur' }
        ],
    },
    roleEditVisible: false,
    userRoleList: [] as any,
    allRoles: [] as Array<TransferPropsAlias>,
    stationEditVisible: false,
    userStationTreeLoading: false,
    userStationTree: [],
    stationChecks: [],
    userStationTreeProps: {
        children: 'children',
        label: 'orgName',
        disabled: 'disabled',
    },
    userMenuSetVisible: false,
    menuListTreeProps: {
        children: 'children',
        label: 'name'
    },
    treeLoading: false,
    menuListOnly: [],
    userResours: [],
})
const loadList = () => {
    state.listLoading = true
    systemApi.querySysUserListPage(state.pageParam).then(data => {
        if (data && data.code === 0) {
            state.dataList = data.data.records
            state.total = data.data.totalRow
        } else {
            state.dataList = []
            state.total = 0
        }
    }).catch(() => {
    }).finally(() => {
        state.listLoading = false
    })
}
// 页面加载时
onMounted(() => {
    // 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['1002'])
    // 列表查询
    loadList()
})

//重置
const reSetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    state.pageParam.page = 1
    loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
    state.pageParam.pageSize = val;
    loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.pageParam.page = val;
    loadList()
}
const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue);
		}
	}
}
//删除
const deleteHandle = (id: string | undefined) => {
    if (!id) {
        ElMessage.error('请选择记录！')
        return
    }
    ElMessageBox.confirm('是否确定删除所选记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        systemApi.deleteSysUserInfo(id).then(data => {
            if (data && data.code === 0) {
                ElMessage.success('删除成功')
                loadList()
            } else {
                ElMessage.error(data.message)
            }
        }).catch(() => {
            ElMessage.error("删除失败")
        })
    })
}
//打开新增弹窗
const addOrUpdateHandle = () => {
    state.submitForm = {
        id: '',
        username: '',
        password: '',
        salt: '',
        email: '',
        mobile: '',
        status: '',
        createUserId: '',
        createTime: '',
        staffId: '',
        enterpriseId: '',
        enterpriseName: '',
        staffName: '',
        idType: '',
        idNo: '',
        lastChangeder: '',
        lastChangedTime: '',
        lastChangedPwdTime: '',
        errorTime: '',
        loginStatus: '',
        alterTime: '',
        loginTime: '',
        ordernum: '',
        chkStatus: '',
        orgId: '',
        skin: '',
        accountName: '',
        loginTerminal: '',
        tenantId: userInfos.value.tenantId,
    }
    state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
    state.submitForm = {
        id: row.id,
        username: row.username,
        password: row.password,
        salt: row.salt,
        email: row.email,
        mobile: row.mobile,
        status: row.status,
        createUserId: row.createUserId,
        createTime: row.createTime,
        staffId: row.staffId,
        enterpriseId: row.enterpriseId,
        enterpriseName: row.enterpriseName,
        staffName: row.staffName,
        idType: row.idType,
        idNo: row.idNo,
        lastChangeder: row.lastChangeder,
        lastChangedTime: row.lastChangedTime,
        lastChangedPwdTime: row.lastChangedPwdTime,
        errorTime: row.errorTime,
        loginStatus: row.loginStatus,
        alterTime: row.alterTime,
        loginTime: row.loginTime,
        ordernum: row.ordernum,
        chkStatus: row.chkStatus,
        orgId: row.orgId,
        skin: row.skin,
        accountName: row.accountName,
        loginTerminal: row.loginTerminal,
        tenantId: row.tenantId,
    }
    state.addOrUpdateVisible = true
}
//重置密码
const resetPasswordHandle = (id: string | undefined) => {
    if (!id) {
        ElMessage.error('请选择记录！')
        return
    }
    ElMessageBox.confirm('是否确定重置所选用户的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        systemApi.resetPasswordByUserId(id).then(data => {
            if (data && data.code === 0) {
                ElMessageBox.alert('密码已重置,为避免密码泄露，请通知用户尽快修改密码。重置后密码为：' + data.data)
            } else {
                ElMessage.error(data.message)
            }
        }).catch(() => {
            ElMessage.error("重置密码失败")
        })
    })
}
const setRoleHandle = (id: string ) => {
    state.allRoles = []
    state.userRoleList = []
    state.roleEditVisible = true
    state.submitForm.id = id
    systemApi.getUserRolesByUserId(id).then(data => {
        if (data && data.code === 0) {
            data.data.roles.forEach((item: any) => {
                state.allRoles.push({
                    key: item.id,
                    label: item.roleName,
                } as TransferPropsAlias)
            })
            data.data.userRoles.forEach((item: any) => {
                state.userRoleList.push(item.roleId)
            })
        } else {
            ElMessage.error(data.message)
        }
    }).catch(() => {
        // console.log(e)
        // ElMessage.error("查询失败")
    })
}
const roleEditSubmit = () => {
    systemApi.setUserRolesByUserId(state.submitForm.id, state.userRoleList).then(data => {
        if (data && data.code === 0) {
            ElMessage.success("设置成功")
            state.roleEditVisible = false
        } else {
            ElMessage.error(data.message)
        }
    }).catch(() => {
        ElMessage.error("设置失败")
    })
}
const setStationHandle = (id: string) => {
    state.submitForm.id = id
    state.stationEditVisible = true
    systemApi.getUserStationTree(id).then(data => {
        if (data && data.code === 0) {
            state.userStationTree = data.data.stations
            userStationTreeRef.value!.setCheckedKeys(data.data.userStations)
        } else {
            ElMessage.error(data.message)
        }
    }).catch(() => {
        // ElMessage.error("设置失败")
    })
}
//新增修改提交
const dataFormSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            //提交数据
            const loading = ElLoading.service({
                lock: true,
                text: '处理中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            if (!state.submitForm.id) {
                //新增
                systemApi.saveSysUserInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            } else {
                systemApi.updateSysUserInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }
        }
    })
}

const stationEditSubmit = () => {
    systemApi.setUserStationByUserId(state.submitForm.id, userStationTreeRef.value!.getCheckedKeys(true)).then(data => {
        if (data && data.code === 0) {
            ElMessage.success("设置成功")
            state.stationEditVisible = false
        } else {
            ElMessage.error(data.message)
        }
    }).catch(() => {
        ElMessage.error("设置失败")
    })
}

const setResEditLineHandle = (row:any) => {
    state.menuListOnly = []
    state.userMenuSetVisible = true
    state.submitForm.tenantId = row.tenantId
    state.submitForm.id = row.id
    reLoadResTreeOnly(row.tenantId, row.id)
}
const reLoadResTreeOnly = (tenantId:string, userId:string) => {
    state.treeLoading = true
    if(!tenantId || !userId)
    state.menuListOnly = []
    systemApi.getTenantUserResTree(tenantId, userId).then(data => {
        if (data) {
            state.menuListOnly = data.data.tree
            treeUserMenuOnlyRef.value!.setCheckedKeys(data.data.userResource)
        } else {
            state.menuListOnly = []
        }
    }).finally(() => {
        state.treeLoading = false
    })
}
const resOnlySubmit = () => {
    systemApi.setUserMenuByUserId(state.submitForm.id, treeUserMenuOnlyRef.value!.getCheckedKeys(false)).then(data => {
        if (data && data.code === 0) {
            ElMessage.success("设置成功")
            state.userMenuSetVisible = false
        } else {
            ElMessage.error(data.message)
        }
    }).catch(() => {
        ElMessage.error("设置失败")
    })
}
</script>